package xyz.bali16.application.controller;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;

import org.springframework.ui.Model;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import xyz.bali16.application.core.enums.ApiEnum;
import xyz.bali16.application.core.model.Result;
import xyz.bali16.application.core.utils.IDUtils;
import xyz.bali16.application.core.utils.TimeUtil;
import xyz.bali16.application.entity.User;
import xyz.bali16.application.model.dto.BaiduUserDTO;
import xyz.bali16.application.model.dto.GithubUserDTO;
import xyz.bali16.application.model.dto.QQUserDTO;
import xyz.bali16.application.model.provider.BaiduProvider;
import xyz.bali16.application.model.provider.GithubProvider;
import xyz.bali16.application.model.provider.QQProvider;
import xyz.bali16.application.security.model.BaiduAccessTokenDTO;
import xyz.bali16.application.security.model.GithubAccessTokenDTO;
import xyz.bali16.application.security.model.AuthUserInfo;
import xyz.bali16.application.service.UserService;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.Principal;
import java.util.Map;
import java.util.UUID;

import static xyz.bali16.application.core.model.Result.*;
import static xyz.bali16.application.core.utils.ResultUtils.errorLog;


@RestController
@RequestMapping(BaseController.API + "user")
@Api(tags = "用户授权接口")
@AllArgsConstructor
@Slf4j
public class SecurityController extends BaseController {
    @Autowired
    private final UserService userService;
    @Autowired
    private final TokenEndpoint tokenEndPoint;

    /**
     * OAuth2 第三方认证
     */


    //@Value("${qq.api.unionId}")
    //private int getQQUnionId;
    @Autowired
    private final QQProvider qqProvider;
    @Autowired
    private GithubProvider githubProvider;
    @Autowired
    private BaiduProvider baiduProvider;
    @GetMapping("/info")
    @ApiOperation("获取当前用户信息")
    public Result<AuthUserInfo> getUserInfo() {
        try {
            AuthUserInfo authUserInfo = userService.getAuthUserInfo();
            return success(ApiEnum.GET_SUCCESS, authUserInfo);
        } catch (Exception e) {
            errorLog(log, e, "获取用户信息失败. {}", e.getMessage());
            return failure(ApiEnum.GET_ERROR, "获取用户信息失败", e);
        }
    }

    //@GetMapping("/nav")
    //@ApiOperation("获取当前用户角色的菜单")
    //public Result<NavigationVo> getCurrentUserNavInfo(){
    //    return success(ApiEnum.GET_SUCCESS, menuService.getCurrentUserNav());
    //}

    @PostMapping("/logout")
    @ApiOperation("退出登录")
    public Result<String> logout(HttpServletRequest request, HttpServletResponse response) {
        SecurityContextHolder.clearContext();
        request.getSession().invalidate();
        return response(ApiEnum.OPERATE_SUCCESS);
    }

    @GetMapping("/token")
    public Result<OAuth2AccessToken> token(@ApiIgnore Principal principal,
                                           @ApiIgnore @RequestParam Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {
        try {
            OAuth2AccessToken oAuth2AccessToken = tokenEndPoint.postAccessToken(principal, parameters).getBody();
            return success(ApiEnum.GET_SUCCESS, oAuth2AccessToken);
        } catch (Exception e) {
            errorLog(log, e, "获取用户Token信息失败. {}", e.getMessage());
            return failure(ApiEnum.GET_ERROR, "获取用户Token信息失败", e);
        }
        //Oauth2TokenVO oauth2TokenVO = new Oauth2TokenVO();
        //oauth2TokenVO.setToken(oAuth2AccessToken.getValue());
        //oauth2TokenVO.setRefreshToken(oAuth2AccessToken.getRefreshToken() == null ? "" : oAuth2AccessToken.getRefreshToken().getValue());
        //oauth2TokenVO.setExpiresIn(oAuth2AccessToken.getExpiresIn());
        //oauth2TokenVO.setTokenHead("Bearer ");
        //oauth2TokenVO.setIsDeveloper(0);
        //ComUser user = UserThreadLocal.getUser();
        //if (user != null && user.getDeveloperTypeDictKey() != null) {
        //    if (user.getDeveloperTypeDictKey().equals(10002)) {
        //        oauth2TokenVO.setIsDeveloper(1);
        //    }
        //}
        //return ResponseResult.SUCCESS(oauth2TokenVO);
    }

    @GetMapping("/callbackbaidu")
    public Result<String> callbackBaidu(@RequestParam(name = "code") String code,
                                @RequestParam(name = "state") String state,
                                HttpServletResponse response,
                                HttpServletRequest request) {
        String baiduClientId= "VOBufWAjL1Kr3vQs6bCqhWpO";
        String baiduClientSecret= "uG0IRWAzNmNLSGMmMQGdO58maRKxFzzI";
        String baiduRedirectUri = "http://127.0.0.1:8080/api/user/callbackbaidu";

        BaiduAccessTokenDTO baiduAccessTokenDTO = new BaiduAccessTokenDTO();
        baiduAccessTokenDTO.setGrant_type("authorization_code");
        baiduAccessTokenDTO.setCode(code);
        baiduAccessTokenDTO.setClient_id(baiduClientId);
        baiduAccessTokenDTO.setClient_secret(baiduClientSecret);
        baiduAccessTokenDTO.setRedirect_uri(baiduRedirectUri);
        String accessToken = baiduProvider.getAccessToken(baiduAccessTokenDTO);
        System.out.println(accessToken);
        BaiduUserDTO baiduUser = baiduProvider.getUser(accessToken);

        // System.out.println(baiduUser.getUsername()+baiduUser.getOpenid());
        if (baiduUser != null && baiduUser.getOpenid() != null) {
            User user = new User();
            user.setName("baidu_"+baiduUser.getUsername());
            user.setUsername("baidu_"+baiduUser.getUsername());
            user.setPassword(IDUtils.uuid());
            user.setBaiduId("" + baiduUser.getOpenid());
            user.setGmtCreated(TimeUtil.getNowTimeToSeconds());
            user.setGmtModified(TimeUtil.getNowTimeToSeconds());
            user.setAvatar("https://gss0.bdstatic.com/6LZ1dD3d1sgCo2Kml5_Y_D3/sys/portrait/item/" + baiduUser.getPortrait());
            userService.save(user);
            return success(accessToken);
            //return success("您的账号已成功绑定/更新百度账号！");
        } else {
            // 登录失败，重新登录
            log.error("callback get github error,{}", baiduUser);
            //return "redirect:/forum";
            return failure();
        }
    }

    @GetMapping("/callbackgithub")
    public Result<String> callback(@RequestParam(name = "code") String code,
                                   @RequestParam(name = "state") String state,
                                   HttpServletResponse response) {
        GithubAccessTokenDTO githubAccessTokenDTO = new GithubAccessTokenDTO();
        final String clientId = "3ac071d6ed35626789f0";

        final String clientSecret = "be39e14ecac3a1dcbac83a79f9f5df4225ad4bc8";

        final String redirectUri = "http://127.0.0.1:8080/api/user/callbackgithub";
        githubAccessTokenDTO.setClient_id(clientId);
        githubAccessTokenDTO.setClient_secret(clientSecret);
        githubAccessTokenDTO.setCode(code);
        githubAccessTokenDTO.setRedirect_uri(redirectUri);
        githubAccessTokenDTO.setState(state);
        String accessToken = githubProvider.getAccessToken(githubAccessTokenDTO);
        System.out.println("accessToken" + accessToken);
        GithubUserDTO githubUser = githubProvider.getUser(accessToken);
        System.out.println(githubUser.getName() + githubUser.getId());
        if (githubUser != null && githubUser.getId() != null) {
            User user = new User();
            if(githubUser.getName()==null)
                user.setName("github_"+String.valueOf(githubUser.getId()));
            else{
            user.setName(githubUser.getName());
            }
            user.setPassword(IDUtils.uuid());
            user.setGithubId(String.valueOf(githubUser.getId()));
            user.setGmtCreated(TimeUtil.getNowTimeToSeconds());
            user.setGmtModified(TimeUtil.getNowTimeToSeconds());
            user.setAvatar("/images/avatar/" + (int) (Math.random() * 11) + ".jpg");
            userService.save(user);
            return success(String.valueOf(user));
        } else {
            // 登录失败，重新登录
            log.error("callback get github error,{}", githubUser);
            return failure();
        }

    }

    @GetMapping("/callbackqq")
    public Result<String> callbackQq(@RequestParam(name = "code") String code) {
        final String qqClientId = null;

        final String qqClientSecret = null;

        final String qqRedirectUri = null;
        GithubAccessTokenDTO githubAccessTokenDTO = new GithubAccessTokenDTO();
        githubAccessTokenDTO.setGrant_type("authorization_code");
        githubAccessTokenDTO.setCode(code);
        githubAccessTokenDTO.setClient_id(qqClientId);
        githubAccessTokenDTO.setClient_secret(qqClientSecret);
        githubAccessTokenDTO.setRedirect_uri(qqRedirectUri);
        // System.out.println("code是"+code+"state是"+state);
        String string = qqProvider.getAccessToken(githubAccessTokenDTO);
        String access_token = string.split("&")[0].split("=")[1];
        String openid = qqProvider.getOpenID(access_token);
        QQUserDTO qqUser = qqProvider.getUser(access_token, qqClientId, openid);
        if (qqUser != null && qqUser.getOpenId() != null) {
            User user = new User();
            System.out.println(qqProvider.getUnionId(access_token));
            System.out.println(qqUser);
            //UserInformation
            //if (getQQUnionId == 1) {
            //    user.setQqAccountId(qqProvider.getUnionId(access_token));
            //} else {
            //    user.setQqAccountId(openid);
            //}
            user.setName(qqUser.getNickname());
            user.setQqId(qqUser.getOpenId());
            user.setGmtCreated(TimeUtil.getNowTimeToSeconds());
            user.setGmtModified(TimeUtil.getNowTimeToSeconds());
            user.setAvatar(qqUser.getFigureurl_qq());
            System.out.println(user);
            userService.save(user);
            //userInfo.setSex(qqUser.getGender());
            //if (StringUtils.isBlank(qqUser.getProvince())) qqUser.setProvince("全部");
            //if (StringUtils.isBlank(qqUser.getCity())) qqUser.setCity("全部");
            //userInfo.setLocation(qqUser.getProvince() + "-" + qqUser.getCity() + "-全部");
            //if (!StringUtils.isBlank(qqUser.getConstellation())) userInfo.setConstellation(qqUser.getConstellation());
            //userInfo.setBirthday(qqUser.getYear() + "-10-10");
            //UserDTO loginuser = (UserDTO) request.getAttribute("loginUser");
            //int flag = userService.createOrUpdateQq(user, loginuser, userInfo);
        /*    if (flag == 1) {//创建qq账号
                model.addAttribute("rsTitle", "成功啦！！！");
                model.addAttribute("rsMessage", "您已使用QQ账号成功注册本站！");
            }*/
            //if (flag == 2) {
               /* model.addAttribute("rsTitle", "成功啦！！！");
                model.addAttribute("rsMessage", "您的账号已成功绑定/更新QQ账号！");*/

         /*   if (flag == 3) {
                model.addAttribute("rsTitle", "成功啦！！！");
                model.addAttribute("rsMessage", "您已使用QQ账号成功登陆本站！");
            }*/

            return success();
        } else {
            log.error("callback get qq error,{}", qqUser);
            return failure();
        }
    }

}
